define(function (require, exports, module) {
    require("apps/grid");
    exports.init = function (ctx, uuid) {
        var _pageComponent = new $.PageDomFactory(uuid);
        var pageListComponent = new $.PageListComponent(uuid, {
            view: {
                grid: "dg_org",
                myToolbar: "nsdb",
                colbar: "org_tempate"
            },
            configs: {
                gridTitle: "小组列表",
                gridUrl: ctx + '/app/api/organization/findAllByPage',
                gridColumns: [
                    {field: 'id', hidden: true},
                    {field: 'checkbox', checkbox: true},
                    {field: 'orgName', title: '小组名称', width: 140},
                    {field: 'depBelong.dirValue', title: '所属科室', width: 140},
                    {field: 'orgJobs', title: '备注', width: 140},
                    {field: 'available', title: '状态', width: 100,
                        formatter: function (value, rec) {
                            return value == "1" ? "启用" : "停用";
                        }
                    }
                ]
            },
            events: {
                renderColBarBefore: function (key, row) {
                    return true;
                },
                onClickColBtn: function (context, btn, row) {
                    switch (btn.key) {
                        case "edit":
                            whenEdit(context, btn.href, row.id);
                            break;
                        case "manage":
                            whenManage(context, btn.href, row);
                            break;
                        case "view":
                            whenView(context, row);
                            break;
                        default :
                            break;
                    }
                },
                onClickToolbarBtn: function (context, btn) {
                    switch (btn.key) {
                        case "search_all":
                            context.searchAll();
                            break;
                        case "search":
                            context.search(btn.href, "小组搜索", "org_search");
                            break;
                        case "add":
                            whenAdd(context, btn.href);
                            break;
                        case "del":
                            context.del(btn.href);
                            break;
                        default :
                            break;
                    }
                }
            }
        });
        var contextWindow = new $.PageWindow();

        function whenView(context, row) {
            context.detail("小组详情", row);
        }

        function whenAdd(context, href) {
            contextWindow.create({
                href: href,
                method: "organization_add_save",
                title: "新增小组",
                callback: function (status) {
                    if (status) {
                        context.grid.datagrid("reload");
                    }
                }
            });
            context.grid.datagrid('clearSelections');
            contextWindow.open();
        }

        function whenEdit(context, href, id) {
            contextWindow.create({
                href: href + "?id=" + id,
                method: "organization_edit_save",
                title: "编辑小组",
                callback: function (status) {
                    if (status) {
                        context.grid.datagrid("reload");
                    }
                }
            });
            contextWindow.open();
        }

        function whenManage(context, href, row) {
            contextWindow.create({
                href: href + "?id=" + row.id,
                title: row.orgName + "成员管理",
                width: 960,
                height: 605
            });
            contextWindow.open();
        }

    };

    exports.add = function (ctx, uuid) {
        var page = new $.PageDomFactory(uuid, true);
        page.getJqDom("available").toggleButton({
            dataRef:{
                "0":"禁用",
                "1":"启用"
            }
        });

        page.getJqDom("depBelong").combobox({
            loadFilter: function (data) {
                return data.content;
            },
            url: WE.contextPath + "/app/api/directory/list?dirGroup=DIRECTORY_DEP_TYPE",
            valueField: 'id',
            textField: 'dirValue',
            editable: false,
            onLoadSuccess:function(){
                var data = page.getJqDom("depBelong").combobox("getData");
                page.getJqDom("depBelong").combobox('select',data[0].id);
            }
        });

        window.organization_add_save = function(win) {
            var postForm = page.getJqDom("form-org-add-info");
            if (!postForm.form('validate')) {
                return false;
            }
            win.wait("start", "保存中,请稍候.");
            var postData = postForm.serializeJson();
            save();
            function save() {
                $.post(postForm.attr("action")
                        + "?random=" + Math.random(), $.utils.buildJson(postData),
                    function (json) {
                        win.wait("end");
                        if ($.utils.isError(json)) {
                            $.messager.alert('信息',
                                json.msg, 'info');
                            win.callback(false);
                        } else {
                            $.messager.alert('信息',
                                '保存成功', 'info');
                            win.callback(true);
                            win.close();
                        }
                    }, "json");
            }

        }
    };

    exports.update = function (ctx, uuid, config) {
        var page = new $.PageDomFactory(uuid, true);
        page.getJqDom("available").toggleButton({
            dataRef:{
                "0":"禁用",
                "1":"启用"
            }
        });

        page.getJqDom("depBelong").combobox({
            loadFilter: function (data) {
                return data.content;
            },
            url: WE.contextPath + "/app/api/directory/list?dirGroup=DIRECTORY_DEP_TYPE",
            valueField: 'id',
            textField: 'dirValue',
            value: config.depBelongId,
            editable: false
        });

        window.organization_edit_save =  function(win) {
            var postForm = page.getJqDom("form-org-update-info");
            if (!postForm.form('validate')) {
                return false;
            }
            var postData = postForm.serializeJson();
            save();
            win.wait("start", "保存中,请稍候.");
            function save(){
                $.post(postForm.attr("action")
                        + "?random=" + Math.random(), postData,
                    function (json) {
                        win.wait("end");
                        if ($.utils.isError(json)) {
                            $.messager.alert('信息',
                                json.msg, 'info');
                            win.callback(false);
                        } else {
                            $.messager.alert('信息',
                                '保存成功', 'info');
                            win.callback(true);
                            win.close();
                        }
                    }, "json");
            }
        }
    };

    exports.search = function (ctx, uuid) {
        var page = new $.PageDomFactory(uuid, true);
        page.getJqDom("available").combobox({
            editable: false
        });

        window.org_search = function(win) {
            win.wait("start", "搜索中,请稍候.");
            var form = page.getJqDom("form-org-search-info");
            var postData = form.serializeJson();
            win.callback(postData);
            win.close();
        }
    };

    exports.addUser = function (ctx, uuid, config) {
        var page = new $.PageDomFactory(uuid, true);

        function addRows(rows) {
            //过滤掉已经选中的
            var ids = queryRows();
            var renderRows = [];
            $.each(rows, function (i, item) {
                if (!ids.contains(item.id)) {
                    renderRows.push(item);
                }
            });
            var htm = Mustache.render('{{#.}}<li data-id={{id}}><span title="{{userName}}">{{userName}}</span><span>({{userNumber}})</span>' +
                '<a href="javascript:void(0)" data-options="iconCls:\'fa fa-trash fa-lg\',plain:true"></a></li>{{/.}}', renderRows);
            $(htm).appendTo(page.getJqDom("orgUsers")).find("a").linkbutton({
                onClick: function () {
                    $(this).parents("li");
                    var parent = $(this).parents("li");
                    var index = page.getJqDom("selected-duty").datagrid("getRowIndex", parent.attr("data-id"));
                    if (index >= 0) {
                        page.getJqDom("selected-duty").datagrid("unselectRow", index);
                    }
                    $(this).parents("li").remove();
                }
            })
        }

        function delRows(rows) {
            var ids = rows.map(function (item) {
                return item.id
            });
            page.getJqDom("orgUsers").find("li").each(function () {
                if (ids.contains($(this).attr("data-id"))) {
                    $(this).remove();
                }
            })
        }

        function queryRows() {
            var ids = [];
            page.getJqDom("orgUsers").find("li").each(function () {
                ids.push($(this).attr("data-id"));
            });
            return ids;
        }

        page.getJqDom("do-query").linkbutton({
            onClick: function () {
                var postData = $(this).parents("form").serializeJson();
                page.getJqDom("selected-duty").datagrid("reload", $.utils.buildJson(postData));
            }
        });

        page.getJqDom("selected-duty").datagrid({
//            url: ctx + '/app/api/organization/addOrgUserList?available=1&orgId=' + config.orgId,
            url: ctx + '/app/api/organization/addOrgUserList?available=1&orgId=' + config.orgId,
            method: 'post',
            toolbar: page.getJqDom("tb2"),
            loader: $.EasyUiLoader,
            pageList: [10, 20, 30, 50],
            pagination: true,
            idField: "id",
            fitColumns: true,
            columns: [
                [
                    {field: 'id', checkbox: true},
                    {
                        field: 'temp1',
                        hidden: true
                    },
                    {
                        field: 'userNumber',
                        title: '用户名',
                        width: 50,
                        align: 'left'
                    },
                    {
                        field: 'userName',
                        title: '姓名',
                        width: 50,
                        align: 'left'
                    },
//                    {
//                        field: 'orgsDescription',
//                        title: '小组',
//                        width: 100,
//                        align: 'left'
//                    },
                    {
                        field: 'available',
                        title: '状态',
                        width: 50,
                        align: 'left',
                        formatter: function (value, row, index) {
                            if (value == "1"
                                && value != null) {
                                return "启用";
                            } else {
                                return "禁用";
                            }
                        }
                    }
                ]
            ],
            onSelect: function (index, data) {
                addRows([data]);
            },
            onUnselect: function (index, data) {
                delRows([data]);
            },
            onSelectAll: function (rows) {
                addRows(rows);
            },
            onUnselectAll: function (rows) {
                delRows(rows);
            },
            onLoadSuccess: function () {
                var $this = $(this);
                var ids = queryRows();
                $.each(ids, function (i, item) {
                    $this.datagrid("selectRecord", item);
                })
            }
        });

        window.organization_add_user_save = function(win) {
            var ids = [];
            page.getJqDom("orgUsers").find("li").each(function () {
                ids.push($(this).attr("data-id"));
            });
            win.wait("start", "保存中,请稍候.");
            if (!ids.length) {
                $.messager.alert('信息',
                    '未选择要添加到小组的用户', 'info');
                win.wait("end");
                return;
            }
            $.post(ctx + "/app/api/organization/addOrgUsers"
                    + "?random=" + Math.random(), $.utils.buildJson({id: config.orgId, userIds: ids}),
                function (json) {
                    win.wait("end");
                    if ($.isPlainObject(json) && json.error) {
                        $.messager.alert('信息',
                            json.msg, 'info');
                        win.callback(false);
                    } else {
                        $.messager.alert('信息',
                            '保存成功', 'info');
                        win.callback(true);
                        win.close();
                    }
                }, "json");
        }
    };
});